package com.cq.hd.merchant.biz;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cq.hd.common.entity.MerchantAppLoginUser;
import com.cq.hd.common.enums.biz.SubOrderStateEnum;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Result;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.BeanUtils;
import com.cq.hd.common.utils.GenerateUtil;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.merchant.dto.EnrollPendingPrintDto;
import com.cq.hd.merchant.utils.FeieUtil;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.dto.ActiveEnrollInfoSonDto;
import com.cq.hd.order.api.dto.MerchantOrderExportDto;
import com.cq.hd.order.api.dto.MerchantOrderPageDto;
import com.cq.hd.order.api.excel.*;
import com.cq.hd.order.api.vo.MerchantOrderExportVo;
import com.cq.hd.order.api.vo.MerchantOrderPageVo;
import com.cq.hd.order.api.vo.MerchantOrderStatisticsVo;
import com.cq.hd.order.api.vo.OrderItemVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class OrderBiz {

    @Resource
    private TbOrderItemApi orderItemApi;
    @Resource
    private TbOrderApi orderApi;

    public Boolean printEnrollInfo(String verifyCode, MerchantAppLoginUser merchantAppLoginUser) {
        if (!merchantAppLoginUser.getMerchantUserInfo().getMerchantName().contains("万商")) {
            return Boolean.FALSE;
        }

        OrderItemVo orderItemVo = orderItemApi.getByVerifyCode(verifyCode).unpack();
        if (orderItemVo == null) {
            Throw.isBusinessException("订单不存在");
        }
        if (StringUtils.isBlank(orderItemVo.getEnrollInfo())) {
            Throw.isBusinessException("报名信息不存在");
        }
        EnrollPendingPrintDto enrollPendingPrintDto = getPrintInfo(orderItemVo.getEnrollInfo());
        String printResult = FeieUtil.printLabel(enrollPendingPrintDto.getCustomerName(), enrollPendingPrintDto.getEnterpriseName());
        log.info("[Feie Print] - verifyCode={}, response={}", verifyCode, printResult);
        JSONObject printResultJson = JSONObject.parseObject(printResult);

        return printResultJson.getIntValue("ret") == 0;
    }

    public void export(MerchantOrderExportDto merchantOrderExportDto, HttpServletResponse response) {
        // 商户订单明细
        List<MerchantOrderExportVo> orderList = orderApi.exportMerchantOrder(merchantOrderExportDto).unpack();
        List<MerchantOrderSheet> sheets = orderList.stream()
                .map(e -> {
                    MerchantOrderSheet merchantOrderSheet = BeanUtil.copyProperties(e, MerchantOrderSheet.class);
                    merchantOrderSheet.setSubOrderStateText(SubOrderStateEnum.typeOf(e.getSubOrderState()).getName());
                    return merchantOrderSheet;
                }).collect(Collectors.toList());

        // 商户订单汇总
        MerchantOrderPageDto merchantOrderPageDto = BeanUtil.copyProperties(merchantOrderExportDto, MerchantOrderPageDto.class);
        MerchantOrderStatisticsVo merchantOrderStatisticsVo = orderApi.getMerchantOrderStatistics(merchantOrderPageDto).unpack();
        MerchantOrderStatisticsSheet merchantOrderStatisticsSheet = BeanUtil.copyProperties(merchantOrderStatisticsVo, MerchantOrderStatisticsSheet.class);

        LocalDateTime nowLocalDateTime = LocalDateUtil.getNowLocalDateTime();
        String fileName = "订单" + LocalDateUtil.toLocalDateTimeToString(nowLocalDateTime, "yyyyMMddHHmmss") + GenerateUtil.getRandomNum(6);

        // 多个sheet的输出需要使用ExcelWriter类，这里想要下载成功，需要输出到OutputStream中
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).inMemory(true).build()) {
            // 设置响应类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            // 设置编码格式
            response.setCharacterEncoding("utf-8");
            // 设置跨域
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            // 设置响应头
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");

            WriteSheet orderSheet = EasyExcel.writerSheet(0, "订单明细")
                    .registerWriteHandler(new CustomWriteHandler())
                    .head(MerchantOrderSheet.class).build();
            excelWriter.write(sheets, orderSheet);

            WriteSheet orderSummarySheet = EasyExcel.writerSheet(1, "订单汇总")
                    .registerWriteHandler(new CustomWriteHandler()).head(MerchantOrderStatisticsSheet.class).build();
            excelWriter.write(Collections.singletonList(merchantOrderStatisticsSheet), orderSummarySheet);
        } catch (Exception ioException) {
            ioException.printStackTrace();
        }
    }

    private EnrollPendingPrintDto getPrintInfo(String enrollInfo) {
        List<ActiveEnrollInfoSonDto> enrollList = JSON.parseArray(enrollInfo, ActiveEnrollInfoSonDto.class);
        EnrollPendingPrintDto enrollPendingPrintDto = new EnrollPendingPrintDto();
        for (ActiveEnrollInfoSonDto enroll : enrollList) {
            if (StringUtils.isBlank(enroll.getTitle()) || StringUtils.isBlank(enroll.getContent())) {
                continue;
            }
            if (StringUtils.equals(enroll.getTitle(), "姓名")) {
                enrollPendingPrintDto.setCustomerName(enroll.getContent());
            }
            if (enroll.getTitle().contains("企业名称")) {
                enrollPendingPrintDto.setEnterpriseName(enroll.getContent());
            }
        }
        return enrollPendingPrintDto;
    }



}
